<template>
  <div class="markdown-container">
    <!-- 渲染区 -->
    <div id="markdown-box"></div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">
        {{ $t('msg.article.commit') }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
  import MkEditor from '@toast-ui/editor'
  import '@toast-ui/editor/dist/toastui-editor.css'
  import '@toast-ui/editor/dist/i18n/zh-cn'
  import { onMounted, defineProps, defineEmits, watch } from 'vue'
  import { useStore } from 'vuex'
  import { watchSwitchLang } from '@/utils/i18n'
  import { commitArticle, editArticle } from './commit'

  const props = defineProps({
    title: {
      required: true,
      type: String,
    },
    detail: {
      required: true,
      type: Object,
    },
  })

  const emits = defineEmits(['onSuccess'])

  // Editor实例
  let mkEditor
  // 处理离开页面切换语言导致 dom 无法被获取
  let el
  onMounted(() => {
    el = document.querySelector('#markdown-box')
    initEditor()
  })

  const store = useStore()
  const initEditor = () => {
    mkEditor = new MkEditor({
      el,
      height: '500px',
      // 样式
      previewStyle: 'vertical',
      // 语言
      language: store.getters.language === 'zh' ? 'zh-CN' : 'en',
    })
    // 初始化
    mkEditor.getMarkdown()
  }

  watchSwitchLang(() => {
    // 如果编辑器不存在，直接返回
    if (!el) return
    // 拿到当前编辑器的内容
    const htmlStr = mkEditor.getHTML()
    // 销毁编辑器
    mkEditor.destroy()
    // 重新初始化编辑器
    initEditor()
    // 将内容重新赋值给编辑器
    mkEditor.setHTML(htmlStr)
  })

  // 处理提交
  const onSubmitClick = async () => {
    if (props.detail && props.detail._id) {
      // 编辑文章
      await editArticle({
        id: props.detail._id,
        title: props.title,
        content: mkEditor.getHTML(),
      })
    } else {
      // 创建文章
      await commitArticle({
        title: props.title,
        content: mkEditor.getHTML(),
      })
    }

    mkEditor.reset()
    emits('onSuccess')
  }

  // 编辑相关
  watch(
    () => props.detail,
    (val) => {
      if (val && val.content) {
        mkEditor.setHTML(val.content)
      }
    },
    {
      immediate: true,
    }
  )
</script>

<style lang="scss" scoped>
  .markdown-container {
    .bottom {
      margin-top: 20px;
      text-align: right;
    }
  }
</style>
